<template>
    <!--第一个表格:各区收运数据统计-->
    <a-card :bordered="false"  v-if="!showInfo">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <h2 class="text-center  margin-bottom">{{title}}</h2>
            <a-form layout="inline" @keyup.enter.native="searchQuery">
                <a-row :gutter="24">

                    <a-col :md="8" :sm="24">
                        <a-form-item label="收运时间">
                            <a-range-picker
                                    :placeholder="['开始时间', '结束时间']"
                                    v-model="rangeTime"
                                    format="YYYY-MM-DD"
                                    @change="handleDateChange"
                            />
                        </a-form-item>
                    </a-col>

<!--                    <a-col :md="8" :sm="24">-->
<!--                        <a-form-item label="产生单位">-->
<!--                            <select-customer-list @change="changeCustomer"></select-customer-list>-->
<!--                        </a-form-item>-->
<!--                    </a-col>-->

                    <a-col :md="12" :sm="24" v-if="showSelectArea">
                        <a-form-item label="区域查询">
                            <select-area ref="selectAreaRef" @change="changeArea"></select-area>
                        </a-form-item>
                    </a-col>

                </a-row>
            </a-form>
        </div>
        <!-- 查询区域-END -->

        <div class="table-operator" style="display: flex;justify-content: space-between;align-items: center;">
            <div>
                <a-button type="primary" @click="searchQuery" icon="search">查询数据列表</a-button>
                <a-button type="primary" @click="resetForm">重置查询</a-button>
            </div>
            <div>
                <a-button type="primary" icon="printer" v-print="'#printTableList'">打印</a-button>
                <a-button type="primary" icon="download"
                          @click="handleMwExportXlsForImages">
                    导出Excel
                </a-button>
            </div>
        </div>

        <!-- table区域-begin -->
        <div>
            <CheckboxWasteType @change="changeWasteType"></CheckboxWasteType>
        </div>
        <div>
            <a-table
                    ref="table"
                    size="middle"
                    bordered
                    rowKey="id"
                    :columns="columns"
                    :dataSource="dataSource"
                    :pagination="ipagination"
                    :loading="loading"
                    class="j-table-force-nowrap"
                    @change="handleTableChange"
            >
                <template slot="link" slot-scope="text,record">
                    <a href="#" style="color: rgb(63, 228, 241);text-decoration: underline;cursor: pointer;font-weight: bold;"
                       @click="handleShow(record)">
                        {{text}}
                    </a>
                </template>
            </a-table>
        </div>


        <!--打印预览-->
        <div v-show="false">
            <div id="printTableList">
                <h2 style="text-align: center;font-weight: bold;">区/县台账数据信息</h2>
                <h3 v-if="rangeTime.length">时间 ： {{rangeTime[0]}} 至 {{rangeTime[1]}}</h3>
                <a-table
                        size="small"
                        bordered
                        rowKey="id"
                        :columns="columns"
                        :dataSource="dataSource"
                        :pagination="false"

                >
                    <template slot="link" slot-scope="text,record">
                        <span>{{text}}</span>
                    </template>
                </a-table>
            </div>
        </div>
    </a-card>


    <!--第二个表格:具体区/县收运数据统计详情-->
    <a-card :bordered="false"  v-else>
        <div style="text-align: right;">
            <a-button type="link" icon="left" class='icon_goBack' @click='goBack'>返回</a-button>
        </div>
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <h2 style="text-align: center;font-weight: bold;">{{title2}}收运数据详情</h2>
            <a-form layout="inline" @keyup.enter.native="searchQuery2">
                <a-row :gutter="24">
                    <a-col :md="8" :sm="24">
                        <a-form-item label="收运时间">
                            <a-range-picker
                                    :placeholder="['开始时间', '结束时间']"
                                    v-model="rangeTime2"
                                    format="YYYY-MM-DD"
                                    @change="handleDateChange2"
                            />
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item label="产生单位">
                            <select-customer-list @change="changeCustomer2"></select-customer-list>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>
        <!-- 查询区域-END -->
        <div class="table-operator" style="display: flex;justify-content: space-between;align-items: center;">
            <a-button type="primary" @click="searchQuery2" icon="search">查询数据列表</a-button>
            <div style="float: right">
                <a-button type="primary" icon="printer" v-print="'#printTableList'">打印</a-button>
                <a-button type="primary" icon="download"
                          @click="handleMwExportXlsForImages2">
                    导出Excel
                </a-button>
            </div>
        </div>

        <!-- 各区县收运记录详情-->
        <div>
            <CheckboxWasteType @change="changeWasteType"></CheckboxWasteType>
        </div>
        <div>
            <div class="ant-alert ant-alert-success" style="margin-bottom: 16px;">
                <span class="countySum">统计：
                    <span>
                        【共有 {{customerSum}} 家机构，收运的总重量 {{allWasteSum}} kg】其中
                         <span v-for="(item,index) in areaDataStatistic" :key="index" v-if="areaDataStatistic.length>0">
                             【{{item.wasteName}}: {{item.wasteBagSum || 0 }} 袋  {{item.weightSum || 0 }} kg】
                         </span>
                    </span>
                </span>
            </div>
            <div>
                <a-table
                        ref="table2"
                        size="middle"
                        bordered
                        rowKey="id"
                        :columns="columns2"
                        :dataSource="dataSource2"
                        :pagination="ipagination2"
                        :loading="loading2"
                        class="j-table-force-nowrap"
                        @change="handleTableChange2"
                >
                    <template slot="link" slot-scope="text,record">
                        <a href="#" style="color: rgb(63, 228, 241);text-decoration: underline;cursor: pointer;font-weight: bold;"
                           @click="handleShowDetail1(record)">
                            {{text}}
                        </a>
                    </template>
                </a-table>
            </div>

            <!--打印预览-->
            <div v-show="false">
                <div id="printTableList">
                    <h2 style="text-align: center;font-weight: bold;">{{title2}}收运数据详情</h2>
                    <h3 v-if="rangeTime2.length">时间 ： {{rangeTime2[0]}} 至 {{rangeTime2[1]}}</h3>
                    <a-table
                            size="small"
                            bordered
                            rowKey="id"
                            :columns="columns2"
                            :dataSource="dataSource2"
                            :pagination="false"

                    >
                        <template slot="link" slot-scope="text,record">
                            {{text}}
                        </template>
                    </a-table>
                </div>
            </div>

        </div>

        <customer-collector-info ref="customerInfoRef" ></customer-collector-info>

    </a-card>
</template>

<script>
    /**
     * create by Jane
     * 区县台账信息
     */
    import '@/assets/less/TableExpand.less'
    import { mixinDevice } from '@/utils/mixin'
    import { JeecgListMixin } from '@/mixins/JeecgListMixin'
    import SelectArea from '@/components/Jane/SelectArea'
    import SelectCustomerList from '@/components/Jane/SelectCustomerList'
    import { getAction } from '@/api/manage'
    import { downloadFile } from '@/api/manage'
    import { filterObj } from '@/utils/util'
    import CustomerCollectorInfo from './modules/customerCollectorInfo'
    import CheckboxWasteType from '@/components/Jane/CheckboxWasteType'

    export default {
        name: 'RecycleStatistic',
        mixins: [JeecgListMixin, mixinDevice],
        components: {
            CustomerCollectorInfo,
            SelectArea,
            SelectCustomerList,
            CheckboxWasteType,
        },
        data() {
            return {
                title: '各区/县收运数据统计',
                title2: '',
                rangeTime: [],
                rangeTime2: [],
                queryParam: {
                    creatTimeBegin: null,
                    creatTimeEnd: null
                },
                queryParam2: {
                    creatTimeBegin: null,
                    creatTimeEnd: null,
                },
                selCustomerNumber : '',// 查询条件：产生单位
                // 表头
                columns: [],
                columns2: [],
                url: {
                    list: null,   // 小董接口 3.0
                    list2: 'hc/hcRecycleRecord/getCustomerRecycleByArea', // 小董接口,根据点击的区/县下显示医院收运数据
                    exportXlsUrlOkForImages: '/hc/hcRecycleRecord/exportAreaStandingBook', // 小董接口 3.0
                    exportXlsUrlOkForImages2: 'hc/hcRecycleRecord/exportCustomerRecycleByArea'  // 小董接口 3.0
                },
                dictOptions: {},
                wasteTypeStatistic: [], // 废物分类数据统计
                wasteTypeList: [], // 废物类型列表 (原始数据)
                wasteId: [],  // 选择的废物
                showInfo: false, //判断是否显示第二层表格数据
                dataSource2:[],//第二层表格数据
                // 第二层表格分页
                ipagination2: {
                    current: 1, // 当前页
                    pageSize: 10, // 一页的数据限制
                    pageSizeOptions: ['10', '20', '30', '50', '100'], // 指定每页能够显示多少条
                    // 能够展现总数
                    showTotal: (total, range) => {
                        return range[0] + '-' + range[1] + ' 共' + total + '条'
                    },
                    // 是否能够快速跳转至某页
                    showQuickJumper: true,
                    // 是否能够改变 pageSize
                    showSizeChanger: true,
                    // 总数
                    total: 0
                },
                filters2: {},
                loading2: false,
                selArea: null,// 选中的区域
                areaDataStatistic: [], //选中区域的总计
                customerSum:[],//选中区域下的机构数
                allWasteSum:[],//选中区域下的医废总数
                showCustomerCollectorInfo: false,

            }
        },
        created() {
            // 获取到用户登陆的信息
            let userInfo = this.$store.getters.userInfo
            if (userInfo.cityCode) {
                this.queryParam.cityCode = userInfo.cityCode
            }
            if (userInfo.areaCode) {
                this.queryParam.areaCode = userInfo.areaCode
            }
        },
        mounted() {

        },
        computed: {
            showSelectArea: function() {
                let state = true
                let userInfo = this.$store.getters.userInfo
                if (userInfo.provinceCode && userInfo.cityCode && userInfo.areaCode) {
                    state = false
                }
                return state
            }
        },
        methods: {
            async initDictConfig() {
                this.initConfig()
                this.setColumns()
            },
            initConfig(){
                this.queryParam.customerNumber = '';
                this.queryParam.cityCode = ''
                this.queryParam.areaCode = ''
                // 获取到用户登陆的信息
                let userInfo = this.$store.getters.userInfo
                if (userInfo.companysId) {
                    this.queryParam.companysId = userInfo.companysId
                }
                if (userInfo.cityCode) {
                    this.queryParam.cityCode = userInfo.cityCode
                }
                if (userInfo.areaCode) {
                    this.queryParam.areaCode = userInfo.areaCode
                }
                this.queryParam.creatTimeBegin = new Date().MonthFirstDay();
                this.queryParam.creatTimeEnd = new Date().MonthLastDay()
                this.rangeTime = [this.queryParam.creatTimeBegin, this.queryParam.creatTimeEnd];


                let ref = this.$refs.selectAreaRef;
                if(ref && ref.clearSelectArea != undefined){
                    ref.clearSelectArea();
                }
            },
            // 重置筛选表单
            resetForm: function() {
                this.initConfig()
                this.searchQuery()
            },
            handleDateChange(value, dateString) {
                this.rangeTime = dateString
                if (dateString[0]) {
                    this.queryParam.creatTimeBegin = dateString[0]
                }
                if (dateString[1]) {
                    this.queryParam.creatTimeEnd = dateString[1]
                }
            },
            async changeCustomer(value, option) {
                this.queryParam.customerNumber = value
            },
            async changeCustomer2(value, option) {
                this.selCustomerNumber = value
            },
            async changeCompany(value, option) {
                this.queryParam.companysId = value
            },
            // 设置表格头部信息
            setColumns() {
                let data = this.wasteTypeList
                let cols = []
                data.forEach((item, index) => {
                    if (item.wasteTypeName) {
                        let child = [];
                        (item['children'] || []).forEach((val, i) => {
                            let info = this.wasteId.find(v => v === val.id)
                            if (info) {
                                // 塑料输液瓶（袋）、玻璃输液瓶（袋）单位换成kg
                                if(val.id == "1366228898901467138" || val.id == "1366274806234079234"){
                                    val.priceUnit = "kg"
                                }
                                child.push({
                                    title: val.wasteTypeName,
                                    dataIndex: 'id',
                                    key: `${index}-${i}`,
                                    children: [
                                        {
                                            title: '袋/箱数',
                                            align: 'center',
                                            dataIndex: 'id',
                                            key: `${index}-${i}-1-1`,
                                            customRender: function(vv, waste, index) {
                                                let info = (waste['maps']).find((v) => v.wasteId === val.id)
                                                if (info) {
                                                    return  `${info.totalWastePresentNumber || ''}`
                                                }
                                                return ' '
                                            }
                                        },
                                        {
                                            title: `废物量${val.priceUnit ? `(${val.priceUnit})` : ''}`,
                                            align: 'center',
                                            dataIndex: 'id',
                                            key: `${index}-${i}-1-2`,
                                            customRender: function(vv, waste, index) {
                                                let info = (waste['maps']).find((v) => v.wasteId === val.id)
                                                if (info) {
                                                    return `${info.totalWastePresentValue || ''}`
                                                }
                                                return ' '
                                            }
                                        }
                                    ]
                                })
                            }
                        })
                        if (child.length) {
                            let obj = {
                                title: item.wasteTypeName,
                                dataIndex: 'id',
                                key: `${index}`,
                                children: child
                            }
                            cols.push(obj)
                        }
                    }
                })
                this.columns = [
                    {
                        title: '序号',
                        dataIndex: 'id',
                        key: 'rowIndex',
                        width: 60,
                        align: 'center',
                        customRender: (text, row, index) => {
                            return parseInt(index) + 1
                        }
                    },
                    {
                        title: '区/县名称',
                        align: 'center',
                        dataIndex: 'area',
                        key: 'area',
                        scopedSlots: { customRender: 'link' },
                    },
                    {
                        title: '机构数量',
                        align: 'center',
                        dataIndex: 'customerTotal',
                        key: 'customerTotal',
                        // customRender: (value, row, index) => {
                        //     return 100
                        // }
                    },
                    ...cols
                ],
                    this.columns2 = [
                        {
                            title: '序号',
                            dataIndex: '',
                            key: 'rowIndex',
                            width: 60,
                            align: 'center',
                            customRender: function(t, r, index) {
                                return parseInt(index) + 1
                            }
                        },
                        {
                            title: '产生单位',
                            align: 'center',
                            dataIndex: 'customerName',
                            scopedSlots: { customRender: 'link' },
                        },
                        ...cols,
                    ]

            },

            async changeArea({ area, city }) {
                if (city) {
                    this.queryParam.cityCode = city
                }
                if (area) {
                    this.queryParam.areaCode = area
                }
            },

            // 废物类型选择改变
            changeWasteType(info,wasteList) {
                this.wasteId = info.ids;
                this.queryParam.wasteId = info.ids.join(',');
                this.wasteTypeList = wasteList;
                this.url.list = '/hc/hcRecycleRecord/getAreaStandingBookV2';
                this.loadData()
                this.setColumns()
            },

            searchQuery: function() {
                this.queryParam.wasteId = this.wasteId.join(',')
                this.loadData(1)
            },

            // 根据区县名称查询医院收运详情
            handleShow : function(row) {
                this.rangeTime2 = this.rangeTime;
                if(row){
                    this.showInfo = true;
                    this.title2 = row.area;
                    this.selArea = row.area;
                    this.loadData2(1);
                }
            },

            handleDateChange2(value, dateString) {
                this.rangeTime2 = dateString
                if (dateString[0]) {
                    this.queryParam2.creatTimeBegin = dateString[0]
                }
                if (dateString[1]) {
                    this.queryParam2.creatTimeEnd = dateString[1]
                }
            },
            // 加载数据源
            loadData2(arg) {
                if (!this.url.list2) {
                    this.$message.error('请设置url.list2属性!')
                    return
                }
                //加载数据 若传入参数1则加载第一页的内容
                if (arg === 1) {
                    this.ipagination2.current = 1
                }
                //查询条件
                let params = this.getQueryParams2();
                getAction(this.url.list2, params).then((res) => {
                    if (res.success) {
                        this.dataSource2 = res.result.records || []
                        this.areaDataStatistic = res.result.waste || []
                        this.allWasteSum = res.result.allWasteSum || 0
                        this.customerSum = res.result.customerSum || 0
                        //当前查询条件下所有的记录数量
                        this.ipagination2.total = res.result.total
                    }
                })
                this.loading2 = false

            },
            getQueryParams2() {
                //获取查询条件
                let sqp = {
                    area : this.selArea,
                    customerNumber : this.selCustomerNumber,

                }
                // 格式化时间
                this.queryParam2 = {
                    creatTimeBegin : this.rangeTime2[0],
                    creatTimeEnd : this.rangeTime2[1],
                    wasteId : this.wasteId.join(','),
                }
                var param = Object.assign(sqp, this.queryParam2, this.filters2)
                param.field = this.getQueryField2()

                param.pageNo = this.ipagination2.current
                param.pageSize = this.ipagination2.pageSize
                return filterObj(param)
            },
            // 第二层查询
            searchQuery2(){
                this.loadData2(1)
            },
            handleTableChange2(pagination, filters, sorter) {
                //分页、排序、筛选变化时触发
                //TODO 筛选
                if (Object.keys(sorter).length > 0) {
                    this.isorter2.column = sorter.field
                    this.isorter2.order = 'ascend' == sorter.order ? 'asc' : 'desc'
                }
                this.ipagination2 = pagination
                this.loadData2()
            },

            getQueryField2() {
                //TODO 字段权限控制
                var str = 'id'
                this.columns2.forEach(function(value) {
                    str += ',' + value.dataIndex
                })
                return str
            },

            // 查看各区域详情取消按钮，返回上一层
            goBack() {
                this.showInfo = false;
                this.selCustomerNumber = '';
            },

            // 根据机构查询机构收运信息详情
            handleShowDetail1 : function(row) {
                this.showCustomerCollectorInfo = true;
                let _this = this;
                if(row){
                    let ref = _this.$refs.customerInfoRef;
                    if(ref){
                        ref.show(row,this.queryParam2);
                    }
                }
            },
            // 下载文件
            handleMwExportXlsForImages() {
                if (this.wasteId.length) {
                    this.queryParam.wasteId = this.wasteId.join(',')
                    let nameList = []
                    this.wasteTypeList.forEach((item) => {
                        let child = item['children'] || [];
                        child.forEach((val) => {
                            // 如果是选中的状态，则追加在wasteList中
                            if(val.checked){
                                nameList.push({...val});
                            }
                        })
                    })
                    let wasteName = []
                    this.wasteId.forEach((val) => {
                        let info = nameList.find(item => val === item.id)
                        if (info) {
                            wasteName.push(info['wasteTypeName'])
                        }
                    })
                    this.queryParam.wasteName = wasteName.join(',')
                } else {
                    this.$message.warning('选择至少一个废物类型导出！')
                    return
                }
                let param = { ...this.queryParam }
                let name = `区/县台账-${new Date().FormatDate()}.xls`
                downloadFile(this.url.exportXlsUrlOkForImages, name, param)
            },

            // 下载文件
            handleMwExportXlsForImages2() {
                if (this.wasteId.length) {
                    this.queryParam2.wasteId = this.wasteId.join(',')
                    let nameList = []
                    this.wasteTypeList.forEach((item) => {
                        let child = item['children'] || [];
                        child.forEach((val) => {
                            // 如果是选中的状态，则追加在wasteList中
                            if(val.checked){
                                nameList.push({...val});
                            }
                        })
                    })
                    let wasteName = []
                    this.wasteId.forEach((val) => {
                        let info = nameList.find(item => val === item.id)
                        if (info) {
                            wasteName.push(info['wasteTypeName'])
                        }
                    })
                    this.queryParam2.wasteName = wasteName.join(',')
                    this.queryParam2.area = this.selArea
                    this.queryParam2.customerNumber = this.selCustomerNumber
                } else {
                    this.$message.warning('选择至少一个废物类型导出！')
                    return
                }
                let param = { ...this.queryParam2 }
                let title = this.title2
                let name = `${title}收运数据详情-${new Date().Format('yyyy-MM-dd')}.xls`
                downloadFile(this.url.exportXlsUrlOkForImages2, name, param)
            }
        }
    }
</script>
<style scoped>
    @import '~@assets/less/common.less';
    .icon_goBack{
        font-size: 25px;
        letter-spacing: 8px;
    }
    .countySum{
        font-weight: 600;
        color:#F5F5F5;
    }
</style>

